/**
 @ Name：layui.aliyunVod 阿里云视频点播
	注意：需要服务器和回调配合
 */


layui.define(['upload', 'form'], function(exports) { //假如该组件依赖 layui.form
	var $ = layui.$,
		form = layui.form,
		upload = layui.upload,
		successCount = 0,
		successFiles = {},
		//字符常量
		MOD_NAME = 'aliyunVod',
		ELEM = '.layui-aliyunVod'
		//外部接口
		,
		aliyunVod = {
			index: layui.aliyunVod ? (layui.aliyunVod.index + 10000) : 0

				//设置全局项
				,
			set: function(options) {
					var that = this;
					that.config = $.extend({}, that.config, options);
					return that;
				}

				//事件监听
				,
			on: function(events, callback) {
				return layui.onevent.call(this, MOD_NAME, events, callback);
			}
		}

		//操作当前实例
		,
		thisAliyunVod = function() {
			var that = this,
				options = that.config,
				id = options.id || options.index;

			return {
				reload: function(options) {
					that.reload.call(that, options);
				},
				config: options
			}
		}

		//构造器
		,
		Class = function(options) {
			var that = this;
			that.index = ++aliyunVod.index;
			that.config = $.extend({}, that.config, aliyunVod.config, options);
			that.render();
		};

	var modFile = layui.cache.modules['aliyunVod'];
	var modPath = modFile.substring(0, modFile.lastIndexOf('/'))
	//默认配置
	Class.prototype.config = {
		callback: false, //是否回调 默认false
		multiple: false, //是否多文件长传
		number: 20, //可上传张数，多文件上传有效
		allDone: function(result) { //所有上传陈工回调

		},
		success: function(result) { //单个上传回调

		},
		fail: function(e) { //报错回调

		},
		progress: function(e) { //上传进度

		},
	};

	//渲染视图
	Class.prototype.render = function() {
		var that = this,
			options = that.config;

		options.elemEvent = $(options.elem);

		var multiple = options.multiple;

		if (!options.fileType) {
			layer.msg('请选择文件类型');
			return;
		}

		if ("images|video|audio|file".indexOf(options.fileType) == -1) {
			layer.msg('不支持选择的文件类型');
			return;
		}
		var exts = options.fileSuffix;
		switch (options.fileType) {
			case 'images':
				if (!options.fileSuffix) {
					exts = 'jpg|png|gif|bmp|jpeg';
				}
				break;
			case 'video':
				if (!options.fileSuffix) {
					exts = 'mp4';
				}
				break;
			case 'audio':
				if (!options.fileSuffix) {
					exts = 'mp3';
				}
				break;
			case 'file':
				if (!options.fileSuffix) {
					exts = 'png|gif|apng|mov|srt|ass|stl|ttml|vtt|jpg|gif|png|mp4|mat|zip';
				}
				break;
		}
		let extsArray = exts.split('|');
		let acceptMime = [];
		for (var i = 0; i < extsArray.length; i++) {
			acceptMime.push((options.fileType == 'images' ? 'image' : options.fileType) + '/' + extsArray[
				i])
		}
		if (multiple) { //多文件上传
			options.number = options.number ? options.number : 20;
			var uploadInst = upload.render({
				elem: options.elem,
				multiple: true,
				auto: false,
				accept: options.fileType,
				exts: exts,
				number: options.number,
				acceptMime: acceptMime.join(","),
				//url: options.policyUrl, //改成您自己的上传接口
				choose: function(obj) {
					options.item = this.item[0];
					console.log(uploader.listFiles())
					var files = that.files = obj.pushFile(); //将每次选择的文件追加到文件队列
					var count = 0;
					for (var fileKey in files) {
						count++;
					}
					if (this.number == 0 || count > this.number) {
						layer.msg('上传个数超出限定', {
							icon: 5
						});
						obj.preview(function(index, file, result) {
							delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
						});
						return;
					}
					layer.msg('上传中', {
						icon: 16,
						time: 0
					});
					var c = 0;
					obj.preview(function(index, file, result) {
						c ++;
						var name = file.name;
						var paramData = '{"Vod":{}}';
						uploader.addFile(file, null, null, null, paramData);
						console.log(c,count)
						if(c >= count){
							setTimeout(function(){
								uploader.startUpload();
								obj.preview(function(index, file, result) {
									delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
								});
							},200)
						}
					});
				},
				done: function(res) {

				},
				error: function() {

				}
			});
			that.uploadInst = uploadInst;
		} else { //单文件上传
			//常规使用 - 普通图片上传
			var uploadInst = upload.render({
				elem: options.elem,
				multiple: false,
				auto: false,
				accept: options.fileType,
				exts: exts,
				acceptMime: acceptMime.join(","),
				//url: options.policyUrl, //改成您自己的上传接口
				choose: function(obj) {
					options.item = this.item[0];
					layer.msg('上传中', {
						icon: 16,
						time: 0
					});
					obj.preview(function(index, file, result) {
						var files = {};
						files[file.lastModified] = file;
						that.files = files;
						var name = file.name;
						var paramData = '{"Vod":{}}';
						uploader.addFile(file, null, null, null, paramData);
						
						uploader.startUpload();
					});
				},
				done: function(res) {

				},
				error: function() {
					layer.msg('上传失败');
					setTimeout(function() {
						layer.closeAll(); //疯狂模式，关闭所有层
					}, 2000);
				}
			});
			that.uploadInst = uploadInst;
		}
		console.log(typeof AliyunUpload)
		if (typeof AliyunUpload == 'undefined') {
			$.ajax({ //获取插件
				url: modPath + '/aliyun-upload-sdk/aliyun-upload-sdk-1.5.2.min.js',
				dataType: 'script',
				cache: true,
				async: false,
			});
			$.ajax({ //获取插件
				url: modPath + '/aliyun-upload-sdk/lib/es6-promise.min.js',
				dataType: 'script',
				cache: true,
				async: false,
			});
			$.ajax({ //获取插件
				url: modPath + '/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.13.0.min.js',
				dataType: 'script',
				cache: true,
				async: false,
			});
		}
		var uploader = new AliyunUpload.Vod({
			//userID，必填，只需有值即可。
			userId: "122",
			//分片大小默认1 MB，不能小于100 KB
			partSize: 1048576,
			//并行上传分片个数，默认5
			parallel: 5,
			//网络原因失败时，重新上传次数，默认为3
			retryCount: 3,
			//网络原因失败时，重新上传间隔时间，默认为2秒
			retryDuration: 2,
			//是否上报上传日志到视频点播，默认为true
			enableUploadProgress: false,
			// 添加文件成功
			addFileSuccess: function(uploadInfo) {
				console.log('addFileSuccess', uploadInfo)
				//uploader.startUpload();
			},
			//开始上传
			'onUploadstarted': function(uploadInfo) {
				console.log('onUploadstarted--- uploadInfo', uploadInfo);
				
				//上传方式1，需要根据uploadInfo.videoId是否有值，调用视频点播的不同接口获取uploadauth和uploadAddress，如果videoId有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
				console.log('videoId', uploadInfo.videoId);
				if (uploadInfo.videoId) {
					//如果uploadInfo.videoId存在，调用刷新视频上传凭证接口
					$.ajax({
						url: options.refreshAuth,
						//processData: false,
						//cache: false,
						//contentType: false,
						type: 'Post',
						data: {
							videoId: uploadInfo.videoId,
						},
						//async: false,
						success: function(res) {
							console.log(res)
							if (res.success == 1) {
								uploader.setUploadAuthAndAddress(uploadInfo, res
									.data.UploadAuth, res.data
									.UploadAddress, res.data.VideoId);
							} else {
								layer.msg('获取凭证失败');
								setTimeout(function() {
									layer.closeAll(); //疯狂模式，关闭所有层
								}, 2000);
								uploader.cleanList();
							}
						},
						error: function() {
							layer.msg('获取凭证失败');
							setTimeout(function() {
								layer.closeAll(); //疯狂模式，关闭所有层
							}, 2000);
							uploader.cleanList();
						},
					})
					
				} else {
					//如果uploadInfo.videoId不存在，调用获取视频上传地址和凭证接口
					//从视频点播服务获取的uploadAuth、uploadAddress和videoId，设置到SDK里
					var fileName = that.randomString() + uploadInfo.file.name.substring(uploadInfo.file.name.lastIndexOf('.'));
					$.ajax({
						url: options.policyUrl,
						//processData: false,
						//cache: false,
						//contentType: false,
						type: 'Post',
						data: {
							fileName: fileName,
							title: that.randomString(),
							fileType: options.fileType
						},
						//async: false,
						success: function(res) {
							console.log(res)
							if (res.success == 1) {
								if (options.fileType == 'images') {
									uploadInfo.authURL = res.data.ImageURL;
									uploadInfo.FileURL = res.data.FileURL;
									uploader.setUploadAuthAndAddress(uploadInfo, res
										.data.UploadAuth, res.data
										.UploadAddress, res.data.ImageId);
								} else if (options.fileType == 'video' || options
									.fileType == 'audio') {
									uploader.setUploadAuthAndAddress(uploadInfo, res
										.data.UploadAuth, res.data
										.UploadAddress, res.data.VideoId);
								}
							} else {
								layer.msg('获取凭证失败');
								setTimeout(function() {
									layer.closeAll(); //疯狂模式，关闭所有层
								}, 2000);
								uploader.cleanList();
							}

						},
						error: function() {
							layer.msg('获取凭证失败');
							setTimeout(function() {
								layer.closeAll(); //疯狂模式，关闭所有层
							}, 2000);
							uploader.cleanList();
						},
					})
				}
			},
			//文件上传成功
			'onUploadSucceed': function(uploadInfo) {
				console.log("onUploadSucceed: ", uploadInfo);

				if (options.fileType == 'images') {
					successFiles[uploadInfo.file.lastModified] = {
						'authc': 1,
						'success': 1,
						'data': {
							'fileName': uploadInfo.object,
							//'size': uploadInfo.checkpoint?uploadInfo.checkpoint.fileSize:0,
							//'mimeType': files[uploadInfo.file.lastModified].type,
							'url': `https://${uploadInfo.bucket}.oss-${uploadInfo.region}.aliyuncs.com/${uploadInfo.object}`,
							'id': uploadInfo.videoId,
							'authURL': uploadInfo.authURL,
						}
					};
					options.success(successFiles[uploadInfo.file.lastModified]);
				} else if (options.fileType == 'video' || options.fileType == 'audio') {
					$.ajax({
						url: options.playAuthUrl,
						//processData: false,
						//cache: false,
						//contentType: false,
						type: 'Post',
						data: {
							id: uploadInfo.videoId,
						},
						//async: false,
						success: function(res) {
							console.log(res)
							if (res.success == 1) {
								successFiles[uploadInfo.file.lastModified] = {
									'authc': 1,
									'success': 1,
									'data': {
										'fileName': uploadInfo.object,
										'size': uploadInfo.checkpoint.fileSize,
										//'mimeType': files[uploadInfo.file.lastModified].type,
										'url': `https://${uploadInfo.bucket}.oss-${uploadInfo.region}.aliyuncs.com/${uploadInfo.object}`,
										'id': uploadInfo.videoId,
										'authURL': uploadInfo.authURL,
									}
								};
								successFiles[uploadInfo.file.lastModified].data
									.authUrl = res.data.PlayInfoList.PlayInfo[0]
									.PlayURL;
								options.success(successFiles[uploadInfo.file
									.lastModified]);
							} else {
								layer.msg('获取凭证失败');
								setTimeout(function() {
									layer.closeAll(); //疯狂模式，关闭所有层
								}, 2000);
								uploader.cleanList();
							}
						},
						error: function() {
							layer.msg('获取凭证失败');
							options.success(successFiles[uploadInfo.file
								.lastModified]);
							setTimeout(function() {
								layer.closeAll(); //疯狂模式，关闭所有层
							}, 2000);
							uploader.cleanList();
						},
					})
				}
			},
			//文件上传失败
			'onUploadFailed': function(uploadInfo, code, message) {
				console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code +
					", message:" +
					message);
			},
			//文件上传进度，单位：字节
			'onUploadProgress': function(uploadInfo, totalSize, loadedPercent) {
				console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" +
					totalSize +
					", percent:" + Math.ceil(loadedPercent * 100) + "%");
			},
			//上传凭证超时
			'onUploadTokenExpired': function(uploadInfo) {
				console.log("onUploadTokenExpired");
				//实现时，根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
				//从点播服务刷新的uploadAuth，设置到SDK里

				uploader.resumeUploadWithAuth(uploadAuth);
			},
			//全部文件上传结束
			'onUploadEnd': function(uploadInfo) {
				console.log("onUploadEnd: uploaded all the files", uploadInfo);
				uploader.cleanList();
				options.allDone(successFiles);

				that.successAll();
			}
		});
	}

	//全部上传成功
	Class.prototype.successAll = function(e) {
		var that = this,
			options = that.config;
		layer.msg('上传成功');
		options.elemEvent.next()[0].value = '';
		setTimeout(function() {
			layer.closeAll(); //疯狂模式，关闭所有层
			successCount = 0;
			successFiles = {};
			delete that.files;
		}, 2000)
	}

	//上传失败
	Class.prototype.fail = function(e) {
		var that = this,
			options = that.config;
		options.fail(e);
		layer.msg('上传失败');
		setTimeout(function() {
			layer.closeAll(); //疯狂模式，关闭所有层
		}, 2000)
	}

	// 随机生成32位字符串
	Class.prototype.randomString = function() {
		let len = 32;
		let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678@';
		let maxPos = $chars.length;
		let pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
		}
		return pwd;
	}

	//重置方法
	Class.prototype.reload = function(options) {
		options = options || {};
		delete options.elemEvent;
		var that = this,
			options = that.config = $.extend({}, that.config, options);
		that.uploadInst.reload(options);
	};

	//核心入口
	aliyunVod.render = function(options) {
		var ins = new Class(options);
		return thisAliyunVod.call(ins);
	};

	exports('aliyunVod', aliyunVod);
});
